package com.baba.vote.logic.impl;

import com.baba.vote.constant.VoteConstant;
import com.baba.vote.dao.HtmlLogMapper;
import com.baba.vote.logic.VoteLogic;
import com.baba.vote.pojo.HtmlLog;
import com.baba.vote.pojo.VoteAct;
import com.baba.vote.util.QRCodeUtils;
import com.google.zxing.WriterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * @author moxinHuoHuo
 * @create 2020/4/17 上午2:28
 */
@Component
public class VoteLogicImpl implements VoteLogic {

  @Autowired
  private HtmlLogMapper htmlLogMapper;

  @Value("${base-url}")
  private String baseUrl;

  private static String ENTRANCE_QRCODE_FRONT = "vote_entrance_qrcode";

  private static String RESULT_QRCODE_FRONT = "vote_result_qrcode";

  @Override
  public String createQrcodeResultImg(VoteAct voteAct) {

    StringBuilder fileName = new StringBuilder()
        .append(VoteConstant.SAVE_PATH)
        .append("/")
        .append(RESULT_QRCODE_FRONT).append("_").append(voteAct.getId())
        .append(".jpg");

    try {
      QRCodeUtils.createQRCode(voteAct.getResultImg(), fileName.toString());
    } catch (WriterException | IOException e) {
      e.printStackTrace();
    }

    return fileName.toString();
  }

  @Override
  public String createQrcodeEntranceImg(Integer actId) {

    List<HtmlLog> all = htmlLogMapper.findAll();

    String url;

    StringBuilder fileName = new StringBuilder()
        .append(VoteConstant.SAVE_PATH)
        .append("/")
        .append(ENTRANCE_QRCODE_FRONT).append("_").append(actId)
        .append(".jpg");


    if (all.isEmpty()) {
//      url = "https://www.baidu.com?voteActId=" + actId;
      url = "https://www.baidu.com";
    } else {
//      url = all.get(0).getEntranceUrl() + "?voteActId=" + actId;
      url = all.get(0).getEntranceUrl();
    }

    try {
      QRCodeUtils.createQRCode(url, fileName.toString());
    } catch (WriterException | IOException e) {
      e.printStackTrace();
    }

    return fileName.toString();
  }

}
